package com.lagou.rpc.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName RpcClientHandler
 * @Description
 * @Author playboy
 * @Date 2021/6/5 4:05 下午
 * @Version 1.0
 **/
@Component
@ChannelHandler.Sharable
@Scope("prototype")
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable<String> {

	private ChannelHandlerContext context;

	private String requestMsg;

	private String responseMsg;

	private ReentrantLock reentrantLock = new ReentrantLock();

	private final Condition send = reentrantLock.newCondition();


	public void setRequestMsg(String requestMsg) {
		this.requestMsg = requestMsg;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		context = ctx;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
		responseMsg = s;
		//notify();
		reentrantLock.lock();
		try {
			send.signal();
		} finally {
			reentrantLock.unlock();
		}
	}


	@Override
	public String call() throws Exception {
		context.writeAndFlush(requestMsg);
		//wait();
		reentrantLock.lock();
		try {
			send.await();
		} finally {
			reentrantLock.unlock();
		}
		return responseMsg;
	}
}
